<template>
  <div>
    <a-modal
      :visible="visiable"
      :title="title"
      :cancelText="t('button.cancel')"
      :okText="t('button.determine')"
      width="60%"
      @ok="submit"
      @cancel="cancel"
    >
      <a-form
        ref="refForm"
        :model="modelForm.data"
        :rules="rules"
        :label-col="{ span: 8 }"
        :wrapperCol="{ span: 22 }"
      >
        <a-row>
          <a-col :span="12">
            <a-form-item :label="t('sendingTranscripts.label.selectStudents')" name="recName">
              <a-input v-model:value="modelForm.data.recName" :disabled="disabledForm">
                <template #addonAfter>
                  <div
                    class="primary-color cursor-pointer"
                    @click="openDialog('studentVisible')"
                  >
                    {{ t('button.select') }}
                  </div>
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('sendingTranscripts.label.selectSemester')" name="semester">
              <a-select
                v-model:value="modelForm.data.year"
                style="width: 110px"
                :placeholder="t('placeholder.pleaseSelect')"
                :disabled="disabledForm"
                @select="handleYear"
              >
                <a-select-option
                  v-for="(item, index) in dictLists.data[
                    dictEnum.YEAR
                  ]"
                  :key="index"
                  :value="item.value"
                >
                  {{ item.label || "" }}
                </a-select-option>
              </a-select>
              <a-select
                v-model:value="modelForm.data.quarter"
                style="width: 110px"
                :placeholder="t('placeholder.pleaseSelect')"
                :disabled="disabledForm"
                @select="handleQuarter"
              >
                <a-select-option
                  v-for="(item, index) in dictLists.data[
                    dictEnum.QUARTER
                  ]"
                  :key="index"
                  :value="item.label"
                >
                  {{ item.label || "" }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('sendingTranscripts.label.city')" name="city">
              <a-input :disabled="disabledForm" v-model:value="modelForm.data.city" :placeholder="t('placeholder.pleaseEnter')" :maxlength="100"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('sendingTranscripts.label.express')">
              <a-input :disabled="disabledForm" v-model:value="modelForm.data.trackName" :placeholder="t('placeholder.pleaseEnter')" maxlength="100"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('sendingTranscripts.label.detailedAddress')">
              <a-textarea
                :disabled="disabledForm"
                v-model:value="modelForm.data.addDetail"
                :placeholder="t('placeholder.pleaseEnter')"
                maxlength="255"
                :rows="4"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="'备注'">
              <a-textarea
                :disabled="disabledForm"
                v-model:value="modelForm.data.remark"
                :placeholder="t('placeholder.pleaseEnter')"
                maxlength="255"
                :rows="4"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('sendingTranscripts.label.courierNumber')">
              <a-input :disabled="disabledForm" v-model:value="modelForm.data.trackNum" :placeholder="t('placeholder.pleaseEnter')" maxlength="50"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('sendingTranscripts.label.selectCourse')" name="curDetail">
              <a-input :disabled="disabledForm" v-model:value="modelForm.data.curDetail" maxlength="200">
                <template #addonAfter>
                  <div
                    class="primary-color cursor-pointer"
                    @click="openDialog('courseVisible')"
                  >
                    {{ t('button.select') }}
                  </div>
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <!-- <a-col :span="12"></a-col> -->
          <a-col :span="12">
            <a-form-item :label="t('sendingTranscripts.label.otherAccessories')" name="curUrl">
              <a-upload
                name="files"
                :disabled="disabledForm"
                :file-list="fileList"
                :customRequest="handleUpload"
                @change="handleUploadChange"
              >
                <a-button> <a-icon type="upload" />{{ t('button.upload') }}</a-button>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
    <course
      :visible="formState.courseVisible"
      @submit="handleSubmit($event, 'course')"
      @close="handleClose"
    ></course>
    <student
      :visible="formState.studentVisible"
      @submit="handleSubmit($event, 'student')"
      @close="handleClose"
    ></student>
  </div>
</template>

<script>
import { reactive, toRaw, ref, onMounted, computed } from "vue";
import dictEnum from "@/const/dict";
import { getDictByCodesReturnObj } from "@/tools/get-dict";
import { useI18n } from "vue-i18n";
import { message, Form } from "ant-design-vue";
import course from "./components/course.vue";
import student from "./components/student.vue";

import { save, update, details, upload } from "@/api/module/student/information-tracking";
const useForm = Form.useForm;
export default {
  name: "add",
  components: {
    course,
    student,
  },
  props: {
    visiable: {
      type: Boolean,
      default: false,
    },
    itemId: [String, Number],
    title: String
  },
  setup(props, content) {
    const { t } = useI18n();

    const refForm = ref();
    const fileList = ref([]);

    const formState = reactive({
      subjectList: [],
      courseVisible: false,
      studentVisible: false,
    });
    const disabledForm = computed(() => {
      return modelForm.data.id ? true : false
    })
    const modelForm = reactive({
      data: {
        tranType: 3
      },
    });
    const rules = {
      recName: [
        {
          required: true,
          message: "请选择学生",
          trigger: "blur",
        },
      ],
      semester: [
        {
          required: true,
          validator: (rules, value, callback) => {
            if (!modelForm.data.semester) {
              return Promise.reject('请选择学期')
            }
            return Promise.resolve();
          },
          trigger: "blur",
        },
      ],
      curDetail: [
        {
          required: true,
          message: "请选择课程",
          trigger: "blur",
        },
      ],
      curUrl: [
        {
          required: true,
          validator: () => {
            if (!modelForm.data.curUrl) {
              return Promise.reject('请选择附件')
            }
            return Promise.resolve();
          },
          trigger: "blur",
        },
      ],
    };
    const { resetFields, validate, validateInfos } = useForm(
      modelForm.data,
      rules
    );
    const openDialog = (value) => {
      if (disabledForm.value) return
      formState[value] = true;
    };
    const getDetails = () => {
      const id = props.itemId || "";
      if (!id) return;
      return details({ id })
        .then((result) => {
          if (result.success) {
            modelForm.data = reactive({ ...result.data });
            const quarter = modelForm.data.semester ? modelForm.data.semester.split('-') : []
            modelForm.data.year = quarter[0]
            modelForm.data.quarter = quarter[1]
          }
        })
        .catch((err) => {
          console.log("err: ", err);
        });
    };
    const cancel = () => {
      content.emit("close", "visibleSave");
    };
    const handleSubmit = (value, type) => {
      if (type == 'course') {
        let list = value.map(item => item.courseName)
        modelForm.data.curDetail = list.join(',') || ''
      } else {
        modelForm.data.recName = value.stuName
        modelForm.data.buspId = value.id
      }
    };
    const handleClose = (value) => {
      formState[value] = false;
    };
    const submit = () => {
      refForm.value.validate().then(() => {
        const result = toRaw(modelForm.data);
        result.semester = result.year + '-' + result.quarter;
        if (result.id) {
          cancel();
        } else {
          save(result)
            .then((res) => {
              if (res.success) {
                cancel();
                message.success({ content: "保存成功", duration: 1 });
              } else {
                message.warning({ content: "保存失败", duration: 1 });
              }
            })
            .catch((err) => {
              console.log("err: ", err);
            });
        }
      });
    };

    // 上传文件
    const handleUpload = (data) => {
      const formData = new FormData();
      formData.append("file", data.file);
      upload(formData).then((res) => {
        if (res.code === 500) {
          message.error({ content: "上传附件失败" });
          data.onError();
        } else {
          data.onSuccess(res.data);
        }
      });
    };
    // 附件
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      resFileList = resFileList.slice(-1);
      resFileList = resFileList.map((file) => {
        if (file.response) {
          file.url = file.response.path;
          modelForm.data.curUrl = file.response.path;
        }
        return file;
      });
      fileList.value = resFileList;
    };
    getDetails();
    const handleQuarter = (value) => {
      modelForm.data.semester = value
    }
    const handleYear = (value) => {
      modelForm.data.semester = value
    }
    const dictLists = reactive({
      data: {}
    })
    onMounted(async () => {
      dictLists.data = await getDictByCodesReturnObj([
        dictEnum.COURSE_TYPE, // 课程类型
        dictEnum.PRE_TYPE, // 优惠类型
        dictEnum.QUARTER, // 季度
        dictEnum.YEAR, // 年份
        dictEnum.SEMESTER_PERIOD, // 学期时段
        dictEnum.CREDITS, // 学分
      ]);
    });
    return {
      t,
      formState,
      modelForm,
      refForm,
      fileList,
      rules,
      dictEnum,
      dictLists,
      cancel,
      submit,
      handleSubmit,
      handleClose,
      handleUpload,
      openDialog,
      handleUploadChange,
      handleQuarter,
      handleYear,
      resetFields,
      validateInfos,
      disabledForm
    };
  },
};
</script>

<style scoped>
</style>
